package com.ff.discounts
import android.app.Application
import android.text.TextUtils
import com.alibaba.fastjson.JSONObject
import com.ff.discounts.component.liteorm.LiteORMUtil
import com.ff.discounts.library.log.HiConsolePrinter
import com.ff.discounts.library.log.HiFilePrinter
import com.ff.discounts.library.log.HiLogConfig
import com.ff.discounts.library.log.HiLogManager
import com.ff.discounts.util.PreferenceUtil
import com.ff.discounts.utils.CommonUtils
import com.tencent.mmkv.MMKV
import com.drake.channel.sendEvent
import com.ff.discounts.component.login.LoginStatusChangedEvent

/**
 *
 * @author: fufang
 * @date: 2023/9/25
 */
class AppContext  : Application() {


    /// 初始化项目
    override fun onCreate() {
        super.onCreate()
        com.ff.discounts.AppContext.Companion.instance = this
        //只有主进程才能初始化
        val processName = CommonUtils.getProcessName(this)
        if (!TextUtils.isEmpty(processName)) {
            if (processName == packageName) {
                initApp()
            }
        }

    }
    private fun initApp(){
        initLog()
        initMMKV()
    }

    /**
     * 初始化 腾讯开源的高性能keyValue存储，用来替代系统的SharedPreferences
     */
    private fun initMMKV() {
        val rootDir = MMKV.initialize(this)
    }

    /// 初始化Log
   private fun initLog(){
        HiLogManager.init(
            object : HiLogConfig() {
                override fun injectJsonParser(): JsonParser? {
                    return JsonParser { src -> JSONObject.toJSONString(src) }
                }

                override fun getGlobalTag(): String {
                    return "MApplication"
                }

                override fun enable(): Boolean {
                    return true
                }

                override fun includeThread(): Boolean {
                    return true
                }

                override fun stackTraceDepth(): Int {
                    return 5
                }
            },
            HiConsolePrinter(),
            HiFilePrinter.getInstance(applicationContext.cacheDir.absolutePath, 0)
        )


    }

    fun logout() {
        logoutSilence()
    }

    fun onLogin() {
        loginStatusChanged()
    }

    private fun logoutSilence() {
        //清除登录相关信息
        PreferenceUtil.logout()



        //销毁一些实例，用的实例在获取，这样获取的用户id就是新的用户
        LiteORMUtil.destroy()



        loginStatusChanged()
    }

    private fun loginStatusChanged() {
        sendEvent(LoginStatusChangedEvent())
    }


    companion object {
        const val TAG = "AppContext"

        lateinit var instance: AppContext
    }
}